package com.baiytfp.hf.HFDataExchange.action.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.baiytfp.hf.HFDataExchange.common.model.base.TableName;
import com.baiytfp.hf.HFDataExchange.common.utils.CommonUtil;
import com.baiytfp.hf.baiytfp.common.db.QueryHelper;
import com.baiytfp.hf.baiytfp.hfutils.HFDBHelper;


@Repository
public class AuthDAOImpl {
	
	/**
	 * 
	 * @param tree_type 树类型
	 * @param obj_type 对象类型  1 用户， 2 岗位，3 角色
	 * @param obj_code 对象值 
	 * @return
	 */
	public List<Map> treeDatas( String tree_type, String obj_type , String obj_code ){
		StringBuffer sWhere = new StringBuffer();
		StringBuffer sql = new StringBuffer();
		sql
		.append("select t.*, m.menu_name,   ")
		.append(" 		ifnull(a.node_seq_code,'') node_seq_code, ifnull(a.tree_type,'1') tree_type,  ")
		.append(" 		ifnull(a.is_auth,0) is_auth ,ifnull(a.is_disabled,0) is_disabled,  ifnull(a.id,'0') as is_edit ")
		.append(" from ")
		.append(	TableName.TREE + " t ")
		.append(" 	left join ").append(TableName.MENU + " m on t.id = m.tree_id ")
		.append(" 	left join ( select * from "+TableName.AUTH + " c  ")
		.append(" 					where  ( c.obj_type = ? or c.obj_type is null ) and ( c.obj_code like ? or c.obj_code is null ) ")
		.append(" 	) a on t.id=a.node_seq ")
		.append(" where 1=1 and ( t.is_open=1 or t.is_open is null ) and t.tree_type = ? ")
		.append(" order by t.node_deep asc, t.parent_tree_code, t.node_order asc");
		

//		System.err.println(sql.toString());
		List<Map> list = null;
		try {
			list = HFDBHelper.querySql(sql.toString(), Map.class, new Object[] { obj_type, obj_code, tree_type });
		}catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	public void addAuth( List<Map> list, Connection conn) throws SQLException {
		Object[][] params= new Object[list.size()][];
		
		Map obj = null;
		for(int i=0;i<params.length;i++) {
			obj = list.get(i); 
			params[i]=new Object[] {HFDBHelper.getIDGenerator(),
					obj.get("obj_code"),obj.get("obj_type"),obj.get("node_seq"),obj.get("node_seq_code"),obj.get("tree_type") 
					,obj.get("is_auth"),obj.get("is_disabled")};
		}
		StringBuffer sql = new StringBuffer().append(" insert into ").append(TableName.AUTH)
				.append("(id,obj_code,obj_type,node_seq,node_seq_code,tree_type,is_auth,is_disabled) values(?,?,?,?,?,?,?,?) ");
		QueryHelper.batch( conn,sql.toString(), params);
	}
	
	public void updateAuth( List<Map> list, Connection conn ) throws SQLException {
		Object[][] params= new Object[list.size()][];
		Map obj = null;
		for(int i=0;i<params.length;i++) {
			obj = list.get(i); 
			params[i]=new Object[] {obj.get("is_auth"),obj.get("is_disabled"),obj.get("edit")};
		}
		StringBuffer sql = new StringBuffer().append(" update ").append(TableName.AUTH).append(" set is_auth=?,is_disabled=? where id=? ");
		QueryHelper.batch( conn,sql.toString(), params);
	}
	
	
}
